﻿using Abp.Domain.Repositories;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;
using MyCompanyName.AbpZeroTemplate.Prm.Authorization;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abp.Runtime.Session;
using System.Threading.Tasks;

namespace MyCompanyName.AbpZeroTemplate.Prm.Main
{
    public class TodoAppService : AbpZeroTemplateAppServiceBase, ITodoAppService
    {
        private readonly ProjectManager _projectManager;
        private readonly PermissionService _permissionService;
        private readonly IRepository<Laboratory, int> _laboratoryRepository;
        private readonly IRepository<ProjectSummary, int> _projectSummaryRepository;
        private readonly IRepository<ProjectApplication, int> _projectAppRepository;
        private readonly IRepository<ProjectFollower, int> _projectFollowerRepository;
        private readonly OperationLogManager _operationLogManager;
        public TodoAppService(ProjectManager projectManager,
            PermissionService permissionService,
            IRepository<Laboratory, int> laboratoryRepository,
            IRepository<ProjectSummary, int> projectSummaryRepository,
            OperationLogManager operationLogManager,
             IRepository<ProjectApplication, int> projectAppRepository,
            IRepository<ProjectFollower, int> projectFollowerRepository)
        {
            _projectManager = projectManager;
            _permissionService = permissionService;
            _laboratoryRepository = laboratoryRepository;
            _operationLogManager = operationLogManager;
            _projectSummaryRepository = projectSummaryRepository;
            _projectAppRepository = projectAppRepository;
            _projectFollowerRepository = projectFollowerRepository;
        }


        public List<Dto.GetTodoOutPut> GetTask()
        {
            long userId = AbpSession.GetUserId();

            List<Dto.GetTodoOutPut> result = new List<Dto.GetTodoOutPut>();

            var dt = DateTime.Now;
            var monDay = DateHelper.GetMondayDate(dt).Date;
            var sunDay = DateHelper.GetSundayDate(dt).Date;

            var projects = _projectManager.projectRepository.GetAll().Where(x => x.Status == Status.进行中).ToList();
            foreach (var p in projects)
            {
                var outPut = new Dto.GetTodoOutPut();
                var hasDocument = _permissionService.HasPermission(userId, p.Id, ProjectFunctions.项目文档);
                if (hasDocument)
                {
                    var hasUpload = _permissionService.HasPermission(p.Id, userId, 1, DocmentFunctions.文档上传);
                    if (hasUpload)
                    {
                        var dte = sunDay.AddDays(1).Date;
                        var uploadWeek = _projectManager.projectDocmeutRepository.GetAll()
                            .Where(x => x.ProjectId == p.Id
                                && x.DocTypeId == 1
                                && ((x.CommitDate < dte && x.CommitDate > monDay) || (x.ReportDate < dte && x.ReportDate > monDay))).Count();
                        if (uploadWeek == 0)
                        {
                            outPut.Note = string.Format("{0}{1}~{2}周报未上传", p.ProjectName, monDay.ToString("yyyy-MM-dd"), sunDay.ToString("yyyy-MM-dd"));
                            outPut.Category = "week";
                            outPut.HostId = p.Id;
                            result.Add(outPut);
                        }
                    }
                }
            }

            var labs = _laboratoryRepository.GetAll().Where(x => x.PrincipalId == userId).ToList();

            if (labs != null && labs.Count>0)
            {
                foreach (var lab in labs)
                {
                    var summary = _projectSummaryRepository.GetAll().Where(x => x.FirstTime == monDay.Date && x.LaboratoryId == lab.Id).SingleOrDefault();
                    if (summary == null)
                    {
                        var outPut = new Dto.GetTodoOutPut();
                        outPut.Note = string.Format("{0}({1} ~ {2})概要未填写", lab.Name, monDay.ToString("yyyy-MM-dd"), sunDay.ToString("yyyy-MM-dd"));
                        outPut.Category = "summary";
                        outPut.HostId = lab.Id;
                        result.Add(outPut);
                    }
                } 
            }



            var proapps = _projectAppRepository.GetAll().Where(x => x.AppStatus == AppStatus.未审核).ToList();
            foreach (var item in proapps)
            {

                var hasAuth = _permissionService.HasPermission(userId, item.ProjectId, ProjectFunctions.项目授权);
                if (hasAuth)
                {
                    var u = UserManager.Users.Where(x => x.Id == item.AppUserId).FirstOrDefault();
                    if (u == null)
                        continue;
                    var outPut = new Dto.GetTodoOutPut();
                    outPut.Note = string.Format("{2}于{3} 申请查看项目 {0}({1})",
                        item.ProjectName, item.ProjectNo, u.UserName, item.CreateOn.ToString("yyyy-MM-dd"));
                    outPut.Category = "proapp";
                    outPut.HostId = item.Id;
                    result.Add(outPut);
                }
            }


            return result;
        }


        public List<Dto.GetProjectLog> GetProjectLog()
        { long userId = AbpSession.GetUserId();
        var projects = _projectFollowerRepository.GetAll().Where(x => x.IsDeleted == false && x.UserId == userId).
            Select(x=>x.Project).Where(x => x.Status == Status.进行中).ToList();
            List<int> pId = new List<int>();
            foreach (var p in projects)
            {
                var hasLog = _permissionService.HasPermission((long)AbpSession.UserId, p.Id, ProjectFunctions.项目日志查看);
                if (hasLog)
                {
                    pId.Add(p.Id);
                }
            }
            var result = _operationLogManager.operationLogRepository.GetAll()
                .Where(x => pId.Any(m => m == x.HostId) && x.Operation == HostOperation.项目)
                .OrderByDescending(x => x.Id).Take(50).ToList()
                .Select(x => new Dto.GetProjectLog()
                {
                    ProjectName = _projectManager.projectRepository.Get(x.HostId).ProjectName,
                    LogText = x.Note,
                    CreateOn = x.CreationTime.ToString("yyyy-MM-dd"),
                    CreateBy = UserManager.Users.Where(q => q.Id == x.CreatorUserId).SingleOrDefault().Name
                }).ToList();
            return result;
        }
    }
}
